<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索 -->
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            placeholder="请输入名称"
            clearable
            v-model="listQuery.name"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleFilter"
          >
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增{{ title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table
        style="width: 100%"
        v-loading="listLoading"
        border
        fit
        stripe
        highlight-current-row
        size="small"
        :data="datas"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="#" align="center" type="selection" />
        <el-table-column
          v-for="column in tableColumns"
          :label="column.title"
          :prop="column.key"
          :key="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="210px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
            >
            </el-button>
            <el-button
              type="success"
              icon="el-icon-upload"
              size="mini"
              @click="handleUpload(scope)"
              >图片
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getCardList"
      />
      <!-- 分页 end -->
    </el-card>

    <!-- 对话框 -->
    <el-dialog :title="getTitle" :visible.sync="dialogVisible" width="700px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        size="small"
      >
        <el-form-item label="品鉴名称" prop="name">
          <el-input v-model="form.name" placeholder="品鉴名称" clearable />
        </el-form-item>
        <el-form-item label="开始时间" prop="begin_date">
          <el-date-picker
            v-model="form.begin_date"
            type="date"
            placeholder="选择日期"
            clearable
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="end_date">
          <el-date-picker
            v-model="form.end_date"
            type="date"
            placeholder="选择日期"
            clearable
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="品鉴说明" prop="comment">
          <el-input v-model="form.comment" placeholder="品鉴说明" clearable />
        </el-form-item>

        <el-form-item label="图片">
          <el-image
            style="width: 200px; height: 100px"
            :src="form.image"
            fit="true"
          ></el-image>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSave(false)" size="small"
          >保存</el-button
        >
        <el-button type="success" @click="handleSave(true)" size="small"
          >保存并上传图片</el-button
        >
      </span>
    </el-dialog>
    <!-- 上传文件弹框 -->
    <el-dialog
      title="图片上传"
      :visible.sync="uploadDlgVisible"
      width="50%"
      @close="handleClose"
    >
      <el-form
        :model="uploadForm"
        ref="uploadFormRef"
        size="small"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        status-icon
      >
        <el-form-item label="品鉴名称">
          <el-input
            v-model="form.name"
            placeholder="品鉴名称"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="image">
          <el-upload
            ref="upload"
            name="image"
            action="/api/cards/image_upload/"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture-card"
            :multiple="false"
            :limit="1"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDlgVisible = false" size="small"
          >关闭</el-button
        >
      </span>
    </el-dialog>
    <!-- 上传文件弹框  end-->
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { mapGetters } from "vuex";

import {
  getCards,
  addCard,
  updateCard,
  delCard,
  delCards,
  delCardImage,
} from "@/api/card";

const defaultForm = {
  id: null,
  name: null,
  begin_date: null,
  end_date: null,
  comment: null,
  image: null,
};

const defUploadForm = {
  id: null,
  image: null,
};

export default {
  name: "Card",
  data() {
    return {
      title: "品鉴卡",
      form: Object.assign({}, defaultForm),
      uploadForm: Object.assign({}, defUploadForm),

      formRules: {
        name: [
          { required: true, message: "请输入品鉴卡名称", trigger: "blur" },
        ],

        begin_date: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
        ],
        end_date: [{ required: true, message: "请结束时间", trigger: "blur" }],
      },
      total: 0,
      datas: [],
      retailers: [],
      selections: [],
      listLoading: true,
      fileList: [],

      dialogType: "new",
      dialogVisible: false,
      uploadDlgVisible: false,

      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
      },

      tableColumns: [
        {
          key: "name",
          title: "品鉴名称",
          align: "left",
        },
        {
          key: "begin_date",
          title: "开始时间",
          align: "center",
          width: "120px",
        },
        {
          key: "end_date",
          title: "结束时间",
          align: "center",
          width: "120px",
        },
        {
          key: "comment",
          title: "品鉴说明",
          align: "left",
        },
      ],
    };
  },
  components: {
    Pagination,
  },
  computed: {
    ...mapGetters(["uid", "token"]),
    getTitle() {
      return this.edit ? `修改${this.title}` : `增加${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return {
        card_id: this.uploadForm.id,
      };
    },
  },
  created() {
    this.getCardList();
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
      var card_id = null;
      card_id = file.id;
      if (card_id == null) {
        if (file.response.status_code == 200) {
          card_id = file.response.file.id;
        }
      }

      if (card_id == null) return;

      delCardImage(card_id)
        .then(() => {
          this.form.image = null;
          this.$message.success("删除成功");
        })
        .catch((error) => {
          this.$message.error("删除失败" + error);
        });
    },
    //上传前
    handleBeforeUpload(file) {
      const flag = file.size / 1024 / 1024 <= 10;
      if (!flag) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return flag;
    },
    handleSuccess(res, file, filelist) {
      console.log(res);
      this.fileList = filelist;
      if (res.status_code == 200) {
        this.getCardList();
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },

    getCardList() {
      this.listLoading = true;
      getCards(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getCardList();
    },

    handleUpload(scope) {
      this.form = scope.row;
      this.uploadForm = Object.assign({}, defUploadForm);
      this.uploadForm.id = scope.row.id;
      this.uploadDlgVisible = true;
      if (this.form.image) {
        this.fileList.push({ url: this.form.image, id: this.form.id });
      }
    },

    handleClose() {
      this.fileList = [];
    },

    //添加数据,弹框显示
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = this.form = Object.assign({}, scope.row);

      this.dialogType = "edit";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;

        if (this.dialogType == "edit") {
          res = await updateCard(this.form);
        } else {
          res = await addCard(this.form);
        }

        this.getCardList();

        const { name, begin_date, end_date } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>品鉴名称: ${name}</div>
              <div>开始时间: ${begin_date}</div>
              <div>结束时间: ${end_date}</div>
            `,
          type: "success",
        });
        if (flag) {
          ///弹出上传文件窗口
          this.uploadDlgVisible = true;

          this.uploadForm = Object.assign({}, defUploadForm);
          console.log(res);
          this.uploadForm.id = res.id;
          this.uploadForm.image = res.image;
          if (res.image) {
            this.fileList.push({ url: res.image, id: res.id });
          }
          console.log("uploadForm:", this.uploadForm);
          console.log("fileList:", this.fileList);
          this.$nextTick(() => {
            this.dialogVisible = false;
            // this.$refs.upload.clearFiles();
          });
        } else {
          this.dialogVisible = false;
        }
      });
    },

    //删除数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCard(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delCards(sel_ids);
          this.getCardList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },
  },
};
</script>

<style lang="scss" scoped>
.item {
  margin-top: 8px;
}
</style>